package sdstcom.lbq.one.lbq.adapter;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import sdstcom.lbq.one.R;
import sdstcom.lbq.one.lbq.Databeans.Musicbean;
import sdstcom.lbq.one.lbq.Databeans.Urlbean;

public class MusicAdapter extends BaseAdapter {
    private Context context;
    private LinkedList<Musicbean.DataBean> list;
    private LayoutInflater inflater;
    private int count;
    private HashMap<Integer,Boolean> collectstate;
    private HashMap<Integer,Boolean> playstate;
    private MediaPlayer player;
    private  String itemid=null;
    private Uri uri;
    private Animation ani;
    public MusicAdapter(Context context, LinkedList<Musicbean.DataBean> list) {
        this.context = context;
        this.list = list;
        inflater = LayoutInflater.from(context);
        collectstate=new HashMap<>();
        playstate=new HashMap<>();
        player=new MediaPlayer();
        ani=AnimationUtils.loadAnimation(context,R.anim.musicplay);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final Viewholder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.music_list_item, parent, false);
            holder = new Viewholder(convertView);
            collectstate.put(position,holder.collect.isSelected());
            if (collectstate.get(position)!=null)
            {
                holder.collect.setSelected(collectstate.get(position));
            }

            playstate.put(position,holder.playbutton.isSelected());
             if (playstate.get(position)!=null){
                 holder.playbutton.setSelected(playstate.get(position));
                 if (playstate.get(position)==true)
                 {
                     holder.img.startAnimation(ani);
                 }
             }

            convertView.setTag(holder);
        } else {
            holder = (Viewholder) convertView.getTag();
            ///////////////
            if (collectstate.get(position)==null)
           {
               holder.collect.setSelected(false);
               collectstate.put(position,false);
           }else
           {
               holder.collect.setSelected(collectstate.get(position));
           }
            if (playstate.get(position)==null)
            {
                holder.playbutton.setSelected(false);
                playstate.put(position,false);
            }else
            {
                holder.playbutton.setSelected(playstate.get(position));
                if (playstate.get(position)==true)
                {
                    holder.img.startAnimation(ani);
                }
            }

///////////////////////////////
        }
        holder.title.setText(list.get(position).getTitle());
        holder.subtitle.setText("--关于 《"+list.get(position).getSubtitle()+"》");
        if (list.get(position).getAudio_platform().equals("1")) {
            holder.icon.setImageResource(R.mipmap.xiami_right);
        } else {
            holder.icon.setImageResource(R.mipmap.share_logo);
        }
        ImageOptions options = new ImageOptions.Builder().setCircular(true).build();
        final ImageView img=(ImageView) convertView.findViewById(R.id.music_item_imageView);
        x.image().bind(img, list.get(position).getImg_url(), options);

        holder.collect.setTag(list.get(position).getId());
        holder.smallsubtitle.setText(list.get(position).getSubtitle());
        holder.forword.setText(list.get(position).getForward());
        holder.username.setText(list.get(position).getAuthor().getUser_name());
        holder.collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             if (collectstate.get(position)==null)
             {
                 v.setSelected(true);
                 collectstate.put(position,true);
             }else
             {
                 v.setSelected(!collectstate.get(position));
                 collectstate.put(position,!collectstate.get(position));
             }


            }
        });
        holder.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare(position);
            }
        });
        holder.playbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playercorl(position,v);

                if (playstate.get(position)==false||playstate.get(position)==null){
                    for (int i = 0; i < playstate.size(); i++) {
                        playstate.put(i,false);

                    }
                    v.setSelected(true);
                    playstate.put(position,true);
                    if (playstate.get(position)==true)
                    {
                        holder.img.startAnimation(ani);
                    }
                }else if (playstate.get(position)==true)
                {
                    v.setSelected(false);
                    playstate.put(position,false);
                    holder.img.clearAnimation();
                }

            }
        });
        return convertView;
    }

    private void playercorl(int position,View v) {
        if (itemid==null)
        {

            Toast.makeText(context,"缓冲中",Toast.LENGTH_SHORT).show();
            itemid=list.get(position).getItem_id();
         //   Log.d("mylog",itemid+"one");
            RequestParams pramas=new RequestParams("http://v3.wufazhuce.com:8000/api/music/detail/"+itemid+"?platform=android&version=4.0.2&uuid=ffffffff-acdc-5a02-0a04-a6b66eed847f&channel=91");
            pramas.setConnectTimeout(5000);
            x.http().get(pramas, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Urlbean urlbean=new Gson().fromJson(result,Urlbean.class);
                    uri=Uri.parse(urlbean.getData().getMusic_id());
                  //  Log.d("mylog",urlbean.getData().getMusic_id());
                    try {
                        player.setDataSource(context,uri);
                        player.setLooping(true);
                        player.prepare();
                        player.start();
                       // Log.d("mylog","bofang");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Toast.makeText(context,"缓冲错误",Toast.LENGTH_SHORT).show();

                    Log.d("mylog",ex.toString());
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });

        }
        else if (itemid==list.get(position).getItem_id())
        {
            if (player.isPlaying())
            {
                player.pause();

            }
            if (!player.isPlaying())
            {
                player.start();

            }

        }else
        {

            itemid=list.get(position).getItem_id();
            Log.d("mylog",itemid);
            Toast.makeText(context,"缓冲中",Toast.LENGTH_SHORT).show();
            RequestParams params=new RequestParams("http://v3.wufazhuce.com:8000/api/music/detail/"+itemid+"?platform=android&version=4.0.2&uuid=ffffffff-acdc-5a02-0a04-a6b66eed847f&channel=91");
            params.setConnectTimeout(5000);
            x.http().get(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    Urlbean urlbean=new Gson().fromJson(result,Urlbean.class);
                    String url=urlbean.getData().getMusic_id();
                    Log.d("mylog",url);
                    uri=Uri.parse(url);
                    try {
                        player.setDataSource(context,uri);
                        player.setLooping(true);
                        player.prepare();
                        player.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Toast.makeText(context,"缓冲失败",Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });


        }
    }


    public static class Viewholder {
        private TextView title;
        private TextView subtitle;
        private ImageView icon;
        private ImageView img;
        private TextView smallsubtitle;
        private TextView forword;
        private TextView username;
        private ImageView collect;
        private ImageView share;
        private ImageView playbutton ;
        public Viewholder(View convertView) {

            title = (TextView) convertView.findViewById(R.id.music_item_title);
            subtitle = (TextView) convertView.findViewById(R.id.music_item_subtitle);
            icon = (ImageView) convertView.findViewById(R.id.music_item_icon);
            img = (ImageView) convertView.findViewById(R.id.music_item_imageView);
            smallsubtitle = (TextView) convertView.findViewById(R.id.music_item_subtitle_small);
            forword = (TextView) convertView.findViewById(R.id.music_item_forward);
            username = (TextView) convertView.findViewById(R.id.music_item_username);
            collect = (ImageView) convertView.findViewById(R.id.music_item_collcet);
            share = (ImageView) convertView.findViewById(R.id.music_item_share);
            playbutton = (ImageView) convertView.findViewById(R.id.music_item_playbutton);

        }


    }

    private void showShare(int position) {
        ShareSDK.initSDK(context.getApplicationContext());
        OnekeyShare oks = new OnekeyShare();
//关闭sso授权
        oks.disableSSOWhenAuthorize();
// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle(list.get(position).getShare_info().getTitle());
// titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl(list.get(position).getShare_info().getUrl());
// text是分享文本，所有平台都需要这个字段
        oks.setText(list.get(position).getShare_info().getContent());
// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
// comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
// site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(context.getString(R.string.app_name));
// siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");
// 启动分享GUI
        oks.show(context);
    }
}
